package com.zhang.auth.handle;

import com.zhang.auth.config.ErrorLoginConfig;
import com.zhang.auth.service.ErrorLoginService;
import com.zhang.common.core.constant.MsgTemplate;
import com.zhang.common.log.LogService;
import com.zhang.common.log.constant.LogConstant;
import com.zhang.common.security.handle.AbstractAuthenticationFailureEvenHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Description
 * @Author zsw
 * @Date 2019/10/29 10:16
 * @Version V1.0
 **/
@Slf4j
@Component
public class AuthenticationFailureEvenHandler  extends AbstractAuthenticationFailureEvenHandler {
    @Autowired
    ErrorLoginService errorLoginService;

    @Autowired
    LogService LogService;

    @Autowired
    ErrorLoginConfig errorLoginConfig;



    @Override
    public void handle(AuthenticationException authenticationException, Authentication authentication) {

        log.error("用户：{} 登录失败，异常：{}", authentication.getPrincipal(), authenticationException.getLocalizedMessage());

        //登陆失败 处理业务,只要失败 次数就+1
        Map<String, Object> errorCountMap = errorLoginService.checkErrorLoginCount();

        boolean enabled = errorLoginConfig.isEnabled();
        String s = enabled?MsgTemplate.LOCK_LOGIN:MsgTemplate.UNLOCK_LOGIN;
        LogService.saveAuthLoginLog(String.format(s+MsgTemplate.ERROR_USER_LOGIN_MSG,authentication.getPrincipal(),errorCountMap.get("error_user_login_count"),authenticationException.getLocalizedMessage()),LogConstant.LOG_LEVEL_ERROR);

        LogService.saveAuthLoginLog(String.format(s+MsgTemplate.ERROR_IP_LOGIN_MSG,errorCountMap.get("error_ip"),errorCountMap.get("error_ip_login_count"),authenticationException.getLocalizedMessage()),LogConstant.LOG_LEVEL_ERROR);


    }



}